/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package SwingForms;

import LogicaClasesNew.IcontroladorCategoria;
import LogicaClasesNew.Fabrica;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

/**
 *
 * @author Valentina
 */
public class frmNuevaCategoria extends javax.swing.JInternalFrame {

    private IcontroladorCategoria ICCATE;
    /**
     * Creates new form frmNuevaCategoria
     */
    public frmNuevaCategoria() {
        
        Fabrica fabrica = Fabrica.getInstance();
        ICCATE = fabrica.getControladorCategoria();
        
        
        initComponents();
        iniciarComboBoxCategoria();
        
         KeyListener escucha = new KeyListener() {  
  
            @Override  
            public void keyTyped(final KeyEvent e) {  
                SwingUtilities.invokeLater(new Runnable() {  
                    @Override  
                    public void run() {  
                        JTextField campo = (JTextField) e.getSource();  
                        int posicaoCursor = campo.getCaretPosition();  
                        campo.setText(campo.getText().toUpperCase());  
                        if (posicaoCursor != campo.getCaretPosition()) {  
                            campo.setCaretPosition(posicaoCursor);  
                        }  
                    }  
                });  
            }  
  
            @Override  
            public void keyReleased(KeyEvent e) {  
            }  
  
            @Override  
            public void keyPressed(KeyEvent e) {  
            }  
        };  //FIN KeyListener escucha
        
      //cargo los TextFields con la funcion de convertir TODO a mayuscula
        JTF_CategoriaTitulo.addKeyListener(escucha);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    //@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    
    //CERRAR
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        //Salir
        this.setVisible(false);
    }                                        

    //NUEVA CATEGORIA
                                      
                                         

    private void JCB_CategoriasActionPerformed(java.awt.event.ActionEvent evt) {                                               
    }                                              

                                        

private void iniciarComboBoxCategoria() {
        //CategoriaJpaController jpaCateg = new CategoriaJpaController();
        try {
          
           // List<Categoria> Listadocategorias;
           // Listadocategorias = jpaCateg.findCategoriaEntities();
            for(int i = 0; i < ICCATE.findCategoriaEntities().size(); i++) {
                
                boolean tiene = ICCATE.findCategoriaEntities().get(i).getTieneProductos(); //Se modifico, tenia Boolean
                //Si no tiene productos me interesa mostrarlo
                if (!tiene){
                String nombre = ICCATE.findCategoriaEntities().get(i).getNombre();
                JCB_Categorias.addItem(nombre);
                }
                
                }
        }
        catch (Exception e){
            JOptionPane.showMessageDialog(this, e.getMessage());
        }   
    }
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        JB_NuevaCategNueva = new javax.swing.JButton();
        JB_Salir = new javax.swing.JButton();
        JCB_Categorias = new javax.swing.JComboBox();
        JL_CategoriaTitulo = new javax.swing.JLabel();
        JTF_CategoriaTitulo = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jCheckBox2 = new javax.swing.JCheckBox();
        jCheckBox1 = new javax.swing.JCheckBox();
        jLabel3 = new javax.swing.JLabel();

        setTitle("Nueva Categoria");

        jLabel2.setForeground(new java.awt.Color(153, 153, 153));
        jLabel2.setText("*En el caso de que no se ingrese el Padre, se considerara que sera de Primer Nivel");

        JB_NuevaCategNueva.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Nuevo.png"))); // NOI18N
        JB_NuevaCategNueva.setToolTipText("Nueva Cateogoria");
        JB_NuevaCategNueva.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JB_NuevaCategNuevaActionPerformed(evt);
            }
        });

        JB_Salir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Cerrar.png"))); // NOI18N
        JB_Salir.setToolTipText("Cerrar");
        JB_Salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JB_SalirActionPerformed(evt);
            }
        });

        JCB_Categorias.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione la Categoria Padre" }));
        JCB_Categorias.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JCB_CategoriasActionPerformed(evt);
            }
        });

        JL_CategoriaTitulo.setText("Titulo");

        JTF_CategoriaTitulo.setForeground(new java.awt.Color(141, 7, 104));
        JTF_CategoriaTitulo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                JTF_CategoriaTituloKeyTyped(evt);
            }
        });

        jLabel1.setText("Padre");

        jCheckBox2.setText("Tiene productos");
        jCheckBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox2ActionPerformed(evt);
            }
        });

        jCheckBox1.setText("Sin padre");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/CompleteTodCampos.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(44, 44, 44)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(JL_CategoriaTitulo)
                                .addGap(18, 18, 18)
                                .addComponent(JTF_CategoriaTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(JCB_Categorias, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jCheckBox2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jCheckBox1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3)))
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(146, 146, 146)
                        .addComponent(JB_NuevaCategNueva)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(JB_Salir))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(52, 52, 52)
                        .addComponent(jLabel2)))
                .addContainerGap(54, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jLabel3)
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JTF_CategoriaTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(JL_CategoriaTitulo))
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JCB_Categorias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jCheckBox1))
                .addGap(18, 18, 18)
                .addComponent(jCheckBox2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(JB_NuevaCategNueva)
                    .addComponent(JB_Salir))
                .addGap(40, 40, 40)
                .addComponent(jLabel2)
                .addGap(22, 22, 22))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jCheckBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBox2ActionPerformed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    //CREAR CATEGORIA
    private void JB_NuevaCategNuevaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_NuevaCategNuevaActionPerformed

        //VALIDACIONES... 
        /*________campos vacios________*/
        
        //...Titulo
        if (JTF_CategoriaTitulo.getText().isEmpty()){
            getToolkit().beep();
            JOptionPane.showMessageDialog(null, "Debe digitar un TITULO", "ERROR" ,JOptionPane.ERROR_MESSAGE);
            JTF_CategoriaTitulo.requestFocusInWindow();
            return;
        }
        
        //...Padre
        if (jCheckBox1.isSelected()== false && JCB_Categorias.getSelectedIndex() == 0){
            getToolkit().beep();
            JOptionPane.showMessageDialog(null, "Debe seleccionar un Padre\n                      O\nDebe tildar 'Sin Padre'  ",  "ERROR" ,JOptionPane.ERROR_MESSAGE);
            jCheckBox1.requestFocusInWindow();
            return;
        }
        
        //.......................................................................
        
        
             //CategoriaJpaController jpacat = new CategoriaJpaController();
            //Creo el objeto con la nueva categoria
            //Categoria categoria = new Categoria(JTF_CategoriaTitulo.getText(),jCheckBox2.isSelected());   
            
           
            //Chequeo si tiene padre o no.
            if (jCheckBox1.isSelected()== false){
            
                try {
                            //TIENE PADRE
                           //LE SETEO EL PADRE A DICHA CATEGORIA 
                           //ICCATE.findCategoria(JTF_CategoriaTitulo.getText()).setPadre(ICCATE.findCategoria(JCB_Categorias.getSelectedItem().toString()));

                           //ACTUALIZO LA CATEGORIA CON EL PADRE QUE LE ASIGNE
                           //ICCATE.editCategoria(JTF_CategoriaTitulo.getText());
                           //CREO LA CATEGORIA CON PADRE
                           ICCATE.createCategoriacpadre(JTF_CategoriaTitulo.getText(), JCB_Categorias.getSelectedItem().toString(),jCheckBox2.isSelected());
                           
                           /*Categoria categoriapapa = jpacat.findCategoria (JCB_Categorias.getSelectedItem().toString());
                           categoria.setPadre(categoriapapa);*/

                           //SE AGREGARA AL PADRE EL HIJO NUEVO QUE PASA A TENER
                           ICCATE.addCatHijaToCatPadre(JCB_Categorias.getSelectedItem().toString(), JTF_CategoriaTitulo.getText());

                           //ACTUALIZO LA CATEGORIA PADRE CON SU NUEVO HIJO ASIGNADO
                           ICCATE.editCategoria(JCB_Categorias.getSelectedItem().toString());
                           //categoriapapa.addCategoria(categoria);
                           //crea la nueva categoria

                           //jpacat.create(categoria);
                           
                           JOptionPane.showMessageDialog(this, "La categoria : " +  JTF_CategoriaTitulo.getText() +" fue creada Exitosamente" , "CORRECTO" , JOptionPane.INFORMATION_MESSAGE);
                } catch ( Exception p){
                    getToolkit().beep();
                    JOptionPane.showMessageDialog(this, "Error.. vuelva a ingresar los datos\n" + p);
                }
            
            }
            else {
            
                try {
                //NO TIENE PADRE persiste, la nueva categoria sin padre asociado
                //CREAMOS LA CATEGORIA   **************NUEVO
                ICCATE.createCategoria(JTF_CategoriaTitulo.getText(), jCheckBox2.isSelected());
         
                    
                JOptionPane.showMessageDialog(this, "Categoria Creada Exitosamente");
                JOptionPane.showMessageDialog(this, "La categoria : " +  JTF_CategoriaTitulo.getText() +" fue creada Exitosamente" , "CORRECTO" , JOptionPane.INFORMATION_MESSAGE);
               }catch ( Exception p){
                    getToolkit().beep();
                    JOptionPane.showMessageDialog(this, "Error.. vuelva a ingresar los datos\n" + p);
               }
            }
        this.setVisible(false);
    }//GEN-LAST:event_JB_NuevaCategNuevaActionPerformed

    //CERRAR
    private void JB_SalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_SalirActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_JB_SalirActionPerformed

    /*
    private void JCB_CategoriasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JCB_CategoriasActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_JCB_CategoriasActionPerformed
 */  
    
    
    //LIMITA EL INGRESO A SOLO LETRAS NO NUMEROS
    private void JTF_CategoriaTituloKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_JTF_CategoriaTituloKeyTyped
        
        //evt es el evento provocado
        //char c=evt.getKeyChar();
        //Convertimos a char la tecla que se haya pulsado
      //if(Character.isDigit(c)){
          //Se pregunta si es digito
      //    getToolkit().beep();
          //piiiippp...!!
      //    evt.consume();
          //lo frena..
                
      //}
    }//GEN-LAST:event_JTF_CategoriaTituloKeyTyped

    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton JB_NuevaCategNueva;
    private javax.swing.JButton JB_Salir;
    private javax.swing.JComboBox JCB_Categorias;
    private javax.swing.JLabel JL_CategoriaTitulo;
    private javax.swing.JTextField JTF_CategoriaTitulo;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration//GEN-END:variables
}
